<template>
    <div id="MessagePage">
      <el-container>
        <el-header>
          <h1>收到的公告列表</h1>
          
        </el-header>
        <el-main>
          <el-row align="middle">
            <span style="margin-left: 2.5%; margin-right: 1%;">筛选公告等级: </span>
            <el-select v-model="selectedState" style="width:10%" @change="handleStateChange">
              <el-option
                  v-for="option in priority"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
            <span style="margin-left: 5%; margin-right: 1%;">筛选发送人: </span>
            <el-select v-model="selectedSender" style="width:10%" @change="handleSenderChange">
              <el-option
                  v-for="option in senders"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
            <span style="margin-left: 6%; margin-right: 1%">筛选标题: </span>
            <el-select v-model="selectedTitle" style="width:10%" @change="handleTitleChange">
              <el-option
                  v-for="option in titles"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
            <span style="margin-left:8%; margin-right: 1%;">筛选日期: </span>
            <el-select v-model="selectedDate" style="width:10%" @change="handleDateChange">
              <el-option
                  v-for="option in dates"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </el-row>
          <el-table :data="messages" height="60vh" border @selection-change="handleSelectionChange" style="margin-top: 1%" :row-style="tableRowClass">
            <el-table-column fixed type="selection" width="37%" />
            <el-table-column prop="priority" label="等级" />
            <el-table-column prop="sender" label="发送人" />
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="date" label="日期" />
            <el-table-column fixed="right" label="操作" width="100%">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="handleRowClick(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <el-dialog v-model="dialogVisible" :style="{height: '60vh'}" title="公告内容" width="60%" draggable overflow>
        <div class="dialog-content-right">
          <p><strong>发送人:</strong> {{ selectedMessage.sender }}</p>
          <p><strong>标题:</strong> {{ selectedMessage.title }}</p>
          <p><strong>日期:</strong> {{ selectedMessage.date }}</p>
          <p><strong>内容:</strong></p>
          <div >{{ selectedMessage.content }}</div>
        </div>
      </el-dialog>
      <el-dialog v-model="messageVisible" :style="{height: '60vh'}" title="新建公告" width="60%" draggable overflow :before-close="closeDialog">
        <div class="dialog-content-right">
          <p><strong>等级:</strong></p>
          <div>
            <el-select v-model="newMessage.priority" style="width:10%" placeholder="">
              <el-option
                  v-for="option in priorities"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </div>
          <p><strong>接收人:</strong></p>
          <div>
            <el-select v-model="newMessage.receiver" style="width:10%" placeholder="">
              <el-option
                  v-for="option in receivers"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </div>
          <p><strong>标题:</strong><el-input v-model="newMessage.title"></el-input></p>
          <p><strong>内容:</strong><el-input type="textarea" v-model="newMessage.content" :style="{ textAlign: 'left' } " :autosize="{ minRows: 9}"></el-input></p>
        </div>
        <el-row style="margin-top: 3%" align="middle" justify="center">
          <el-button type="primary" class="custom-button" style="background: #0674e0;border: none; margin-right: 15%;" v-on:click="saveDraft" >保存草稿</el-button>
          <el-button type="primary" class="custom-button" style="background: #0674e0;border: none" v-on:click="sendMessage">发送公告</el-button>
        </el-row>
      </el-dialog>
    </div>
  </template>
  
  <script lang="js">
  import {onMounted, reactive, ref, toRefs, watch} from 'vue';
  import {ElMessage, ElMessageBox} from "element-plus";
  import axios from "axios";
  import store from "@/store";
  
  export default {
    name: 'MessagePage',
    setup() {
      const currentUser = reactive(toRefs(store.state.currentUser));
  
      const newMessage = reactive({
        priority: '',
        receiver: '',
        title: '',
        content: '',
        // sender: currentUser.username, //TODO 登陆用户名
        sender: 'Manager0',
        date: ''
      });
      const messages = ref([]);
      const senders = ref([]);
      const titles = ref([]);
      const dates = ref([]);
      const priority = ref([]);
      const priorities = ref([
        {label: "一级", value: "一级"},
        {label: "二级", value: "二级"},
        {label: "三级", value: "三级"},
        {label: "其它", value: "其它"},
      ]);
      const receivers = ref([
        {label: "医生", value: "医生"},
        {label: "病人", value: "病人"},
        {label: "全部", value: "全部"},
      ]);
  
      const dialogVisible = ref(false);
      const messageVisible = ref(false);
      const save = ref(false);
      const selectedMessage = ref({});
      const selectedSender = ref("");
      const selectedDate = ref("");
      const selectedTitle = ref("");
      const selectedState = ref("");
      const selectedRows = ref([]);
  
      watch(newMessage, () => {
        save.value = false;
      }, { deep: true });
  
      onMounted(() => {
        fetchDataFromDatabase(1);
      });
  
      const fetchDataFromDatabase = (i) => {
        const data = {
          sender: selectedSender.value,
          priority: selectedState.value,
          title: selectedTitle.value,
          date: selectedDate.value,
          receiver: 1
        };
        axios.post('http://localhost:8085/notices', data)  //通过data中的四个是否为全部来判断是否进行筛选
            .then(response => {
              if (response.status === 200) {
                messages.value = response.data;
                if(i){
                  const uniqueSenders1 = Array.from(new Set(messages.value.map(msg => msg.sender)));
                  senders.value = uniqueSenders1.map(sender => ({ label: sender, value: sender }));
                  senders.value.unshift({ label: "所有", value: "所有" });
                  const uniqueSenders2 = Array.from(new Set(messages.value.map(msg => msg.title)));
                  titles.value = uniqueSenders2.map(title => ({ label: title, value: title }));
                  titles.value.unshift({ label: "所有", value: "所有" });
                  const uniqueSenders3 = Array.from(new Set(messages.value.map(msg => msg.date.substring(0, 10))));
                  dates.value = uniqueSenders3.map(date => ({ label: date, value: date }));
                  dates.value.unshift({ label: "所有", value: "所有" });
                  const uniqueSenders4 = Array.from(new Set(messages.value.map(msg => msg.priority)));
                  priority.value = uniqueSenders4.map(priority => ({ label: priority, value: priority }));
                  priority.value.unshift({ label: "所有", value: "所有" });
                }
                ElMessage({
                  type: 'success',
                  message: '载入数据成功',
                });
              } else {
                ElMessage({
                  type: 'error',
                  message: '载入数据失败，请重试',
                });
              }
            })
            .catch((error) => {
              console.error('Error updating user information:', error);
              ElMessage({
                type: 'error',
                message: '载入数据失败，请重试',
              });
            });
      };
  
      const handleRowClick = (row) => {
        selectedMessage.value = row;
        dialogVisible.value = true;
      };
  
      const deleteMessage = (row) => {
        ElMessageBox.confirm(
            '确认删除所选公告？',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              let ids = [row.id]
              axios.post(`http://localhost:8085/notices/delete`, ids)  //将row中对应的数据给到数据库，从中删除对应记录（这里是一条）
                  .then(response => {
                    if (response.status === 200) {
                      fetchDataFromDatabase(1);
                      ElMessage({
                        type: 'success',
                        message: '删除成功',
                      });
                    } else {
                      ElMessage({
                        type: 'error',
                        message: '删除失败，请重试',
                      });
                    }
                  })
                  .catch((error) => {
                    console.error('Error updating user information:', error);
                    ElMessage({
                      type: 'error',
                      message: '删除失败，请重试',
                    });
                  });
            })
            .catch(err => {
              console.error('Error updating user information:', err);
              ElMessage({
                type: 'info',
                message: '删除操作已取消',
              })
            })
      };
  
      const handleDialogClose = () => {
        dialogVisible.value = false;
      };
  
      const handleSenderChange = (sender) => {
        selectedSender.value = sender;
        fetchDataFromDatabase(0);
      }
  
      const handleStateChange = (priority) => {
        selectedState.value = priority;
        fetchDataFromDatabase(0);
      }
  
      const handleDateChange = (date) => {
        selectedDate.value = date;
        fetchDataFromDatabase(0);
      }
  
      const handleTitleChange = (title) => {
        selectedTitle.value = title;
        fetchDataFromDatabase(0);
      }
  
      const handleSelectionChange = (row) => {
        selectedRows.value = row;
        // console.log(selectedRows.value)
      }
  
      const createMessage = () => {
        messageVisible.value = true;
        save.value = false;
      }
  
      const deleteMessages = () => {
        ElMessageBox.confirm(
            '确认删除所选公告？',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              //在这里，将selectedRows转换为合适的数据传给后段
              let ids = selectedRows.value.map(item => item.id);
              axios.post(`http://localhost:8085/notices/delete`, ids) //删除数据库中多条记录（selectedRows中有多条记录），感觉和上面的删单条在后端可以用一个代码处理
                  .then(response => {
                    if (response.status === 200) {
                      fetchDataFromDatabase(1);
                      ElMessage({
                        type: 'success',
                        message: '删除成功',
                      });
                    } else {
                      ElMessage({
                        type: 'error',
                        message: '删除失败，请重试',
                      });
                    }
                  })
                  .catch((error) => {
                    console.error('Error updating user information:', error);
                    ElMessage({
                      type: 'error',
                      message: '删除失败，请重试',
                    });
                  });
            })
            .catch(err => {
              console.error('Error updating user information:', err);
              ElMessage({
                type: 'info',
                message: '删除操作已取消',
              })
            })
        // confirmed.value = true;
      }
  
      const closeDialog = () => {
        ElMessageBox.confirm(
            '请确保草稿已保存。确认退出？',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              messageVisible.value = false;
              if(!save.value){
                refresh();
              }
            })
            .catch(err => {
              console.error('Error updating user information:', err);
              ElMessage({
                type: 'info',
                message: '退出操作已取消',
              })
            })
      }
  
      const refresh = () => {
        newMessage.priority = '';
        newMessage.content = '';
        newMessage.receiver = '';
        newMessage.title = '';
      }
  
      const saveDraft = () => {
        save.value = true
      }
  
      const sendMessage = () => {
        ElMessageBox.confirm(
            '确认发送？',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              const currentDate = new Date().toISOString();
              newMessage.date = currentDate.substring(0, 10) + ' ' + currentDate.substring(11, 19);
              console.log(newMessage);
              axios.post(`http://localhost:8085/notices/add`, newMessage) //将newMessage存到数据中
                  .then(response => {
                    if (response.status === 200) {
                      refresh();
                      messageVisible.value = false;
                      fetchDataFromDatabase(1);
                      ElMessage({
                        type: 'success',
                        message: '发送成功',
                      });
                    } else {  //这里可以根据返回code值的不同判断错误类型，从而进行个性化错误输出
                      ElMessage({
                        type: 'error',
                        message: '发送失败，请重试',
                      });
                    }
                  })
                  .catch((error) => {
                    console.error('Error updating user information:', error);
                    ElMessage({
                      type: 'error',
                      message: '发送失败，请重试',
                    });
                  });
            })
            .catch(err => {
              console.error('Error updating user information:', err);
              ElMessage({
                type: 'info',
                message: '发送已取消',
              })
            })
      };
  
      const tableRowClass = ({ row }) => {
        const priority = row.priority;
        if (priority === '一级') {
          // return 'first-row';
          return { backgroundColor: '#FFCCCC' };
        } else if (priority === '二级') {
          return { backgroundColor: '#FFFFCC' };
        } else if (priority === '三级') {
          return { backgroundColor: '#CCFFFF' };
        } else {
          return '';
        }
      };
  
      return {
        messages,
        dialogVisible,
        selectedMessage,
        selectedDate,
        selectedTitle,
        selectedState,
        handleRowClick,
        handleDialogClose,
        handleSelectionChange,
        selectedSender,
        senders,
        titles,
        dates,
        priority,
        priorities,
        receivers,
        handleSenderChange,
        handleTitleChange,
        handleDateChange,
        handleStateChange,
        createMessage,
        deleteMessages,
        messageVisible,
        newMessage,
        closeDialog,
        saveDraft,
        sendMessage,
        deleteMessage,
        tableRowClass
      };
    },
  };
  </script>
  
  <style scoped>
  #MessagePage {
    padding: 20px;
  }
  
  .dialog-content-right {
    text-align: left;
  }
  
  </style>